package com.lee.limiter.maplimit;

/**
 * User:liwei
 * Date:2017/9/1
 * Time:14:31
 */
public class RateLimitPolicy {

    //间隔单位毫秒。如：每秒为10000 每分为 60000
    private final long intervalInMills;
    //token的数量
    private final long tokenSize;
    // max tokens saved if user don't use the bucket for a long time
    // equals to intervalPerPermit * maxBurstTime
    private final long maxBurstTokens;
    //每个token的生成时间间隔（intervalInMills/tokenSize）
    private final long intervalPerPermit;
    public RateLimitPolicy(long tokenSize, long intervalInMills, long maxBurstMills) {
        this.intervalInMills = intervalInMills;
        this.tokenSize = tokenSize;
        this.intervalPerPermit = intervalInMills / tokenSize;
        this.maxBurstTokens = Math.min(maxBurstMills / intervalPerPermit, tokenSize);
    }

    public long getIntervalInMills() {
        return intervalInMills;
    }

    public long getTokenSize() {
        return tokenSize;
    }

    public long getMaxBurstTokens() {
        return maxBurstTokens;
    }

    public long getIntervalPerPermit() {
        return intervalPerPermit;
    }

    protected String getBucketKey(String identity){
        return new StringBuilder().append("rate:limiter:").append(intervalInMills)
                .append(":tokensize:").append(tokenSize)
                .append(":identity:").append(identity)
                .toString();
    }
}
